package com.etone.smartAudit.service;

import com.alibaba.fastjson.JSON;
import com.etone.smartAudit.domain.Admin;
import com.etone.smartAudit.domain.IapPlatform;
import com.etone.smartAudit.dto.iapPlatform.IapPlatformDTO;
import com.etone.smartAudit.enums.IapDataField;
import com.etone.smartAudit.error.CustomParameterizedException;
import com.etone.smartAudit.mapper.IapPlatformMapper;
import com.etone.smartAudit.mapstruct.IapPlatformMapstruct;
import com.etone.smartAudit.utils.ArraysExtendUtil;
import com.etone.smartAudit.utils.ImageUtil;
import com.etone.smartAudit.vo.FileVO;
import com.etone.smartAudit.vo.PagerVO;
import com.etone.smartAudit.vo.iapPlatform.IapPlatformDetailVO;
import com.etone.smartAudit.vo.iapPlatform.IapPlatformListVO;
import com.etone.smartAudit.vo.iapPlatform.IapPlatformSimpleVO;
import com.etone.smartAudit.vo.iapPlatform.IapPlatformTotalVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author: 蒋学伟
 * @create: 2020-06-21 15:28:26
 * @Description IapPlatformService
 */
@AllArgsConstructor
@Service
public class IapPlatformService {

    private IapPlatformMapper iapPlatformMapper;

    private IapPlatformMapstruct iapPlatformMapstruct;

    private FileUploadService fileUploadService;

    private IapDataModelService iapDataModelService;

    public IapPlatform get(Integer id) {
        IapPlatform iapPlatform = iapPlatformMapper.selectById(id);
        if (iapPlatform == null) {
            throw new CustomParameterizedException("系统不存在");
        }
        return iapPlatform;
    }

    /**
     * 统计平台总数和总元数据
     *
     * @return
     */
    public List<IapPlatformTotalVO> findIapPlatformsDataFieldTotal() {
        List<IapPlatformTotalVO> iapPlatformsDataFieldTotals = iapPlatformMapper.findIapPlatformsDataFieldTotal();
        List<IapDataField> iapDataFields = IapDataField.listOnOther();

        //补充数据
        List<IapPlatformTotalVO> iapPlatformTotalVOS = iapDataFields.stream().map(iapDataField -> {
            Optional<IapPlatformTotalVO> optionalIapPlatformTotalVO = iapPlatformsDataFieldTotals.stream().filter(iapPlatformTotalVO -> iapDataField.equals(iapPlatformTotalVO.getDataField())).findFirst();
            if (optionalIapPlatformTotalVO.isPresent()) {
                return optionalIapPlatformTotalVO.get();
            }
            return IapPlatformTotalVO.builder().dataField(iapDataField).iapDataModelCnt(0).iapPlatformCnt(0).build();
        }).collect(Collectors.toList());
        return iapPlatformTotalVOS;
    }

    /**
     * 查找基本信息列表
     *
     * @param keys
     * @param page
     * @param pageSize
     * @return
     */
    public PagerVO<IapPlatformSimpleVO> listSimple(String keys, int page, int pageSize) {
        Page<IapPlatformSimpleVO> iapPlatformSimpleVOPage = PageHelper.startPage(page, pageSize).doSelectPage(() -> {
            iapPlatformMapper.findListSimple(keys);
        });
        return PagerVO.of(iapPlatformSimpleVOPage);
    }

    /**
     * 系统信息平台列表
     *
     * @param name
     * @param dataField
     * @param page
     * @param pageSize
     * @return
     */
    public PagerVO<IapPlatformListVO> list(String name, IapDataField dataField, int page, int pageSize) {
        Page<IapPlatformListVO> iapPlatformListVOPage = PageHelper.startPage(page, pageSize).doSelectPage(() -> {
            iapPlatformMapper.findList(name, dataField);
        });
        return PagerVO.of(iapPlatformListVOPage);
    }

    /**
     * 增加|编辑平台
     *
     * @param id
     * @param iapPlatformDTO
     * @param admin
     */
    @Transactional(rollbackFor = Exception.class)
    public void save(Integer id, IapPlatformDTO iapPlatformDTO, Admin admin) {
        if (checkNameExists(id, iapPlatformDTO.getName())) {
            throw new CustomParameterizedException("系统名称已存在");
        }
        IapPlatform iapPlatform;
        Date now = new Date();
        List<FileVO> oldAccessBill = null;
        List<FileVO> oldInterfaceDesc = null;
        List<FileVO> oldOtherDesc = null;
        List<FileVO> oldRoleDesc = null;
        String oldCapability = null;
        if (id != null) {
            iapPlatform = get(id);
            oldAccessBill = iapPlatform.getAccessBill() == null ? null : JSON.parseArray(iapPlatform.getAccessBill(), FileVO.class);
            oldInterfaceDesc = iapPlatform.getInterfaceDesc() == null ? null : JSON.parseArray(iapPlatform.getInterfaceDesc(), FileVO.class);
            oldOtherDesc = iapPlatform.getOtherDesc() == null ? null : JSON.parseArray(iapPlatform.getOtherDesc(), FileVO.class);
            oldRoleDesc = iapPlatform.getRoleDesc() == null ? null : JSON.parseArray(iapPlatform.getRoleDesc(), FileVO.class);
            oldCapability = iapPlatform.getCapability();
        } else {
            iapPlatform = IapPlatform.builder().createTime(now).createAdminId(admin.getId()).build();
        }

        iapPlatformMapstruct.copyToIapPlatform(iapPlatform, iapPlatformDTO);
        iapPlatform.setUpdateTime(now);
        iapPlatform.setUpdateAdminId(admin.getId());
        if (id == null) {
            iapPlatformMapper.insert(iapPlatform);
        } else {
            iapPlatformMapper.updateById(iapPlatform);
        }

        //清理图片
        fileUploadService.deleteFileForUpdate(
                ArraysExtendUtil.mergerArraysList(
                        iapPlatformDTO.getAccessBill(),
                        iapPlatformDTO.getInterfaceDesc(),
                        iapPlatformDTO.getOtherDesc(),
                        iapPlatformDTO.getRoleDesc()),
                ArraysExtendUtil.mergerArraysList(
                        oldAccessBill,
                        oldInterfaceDesc,
                        oldOtherDesc,
                        oldRoleDesc)
        );
        fileUploadService.deleteFileForUpdateByURL(
                ImageUtil.getImgTagUrl(iapPlatformDTO.getCapability()),
                ImageUtil.getImgTagUrl(oldCapability)
        );

    }

    /**
     * 获取详情
     *
     * @param id
     * @return
     */
    public IapPlatformDetailVO detail(Integer id) {
        IapPlatform iapPlatform = get(id);
        IapPlatformDetailVO iapPlatformDetailVO = iapPlatformMapstruct.getIapPlatformDetailVO(iapPlatform);
        return iapPlatformDetailVO;
    }

    /**
     * 删除
     *
     * @param id
     */
    public void delete(Integer id) {
        IapPlatform iapPlatform = get(id);
        List<FileVO> oldAccessBill = iapPlatform.getAccessBill() == null ? null : JSON.parseArray(iapPlatform.getAccessBill(), FileVO.class);
        List<FileVO> oldInterfaceDesc = iapPlatform.getInterfaceDesc() == null ? null : JSON.parseArray(iapPlatform.getInterfaceDesc(), FileVO.class);
        List<FileVO> oldOtherDesc = iapPlatform.getOtherDesc() == null ? null : JSON.parseArray(iapPlatform.getOtherDesc(), FileVO.class);
        List<FileVO> oldRoleDesc = iapPlatform.getRoleDesc() == null ? null : JSON.parseArray(iapPlatform.getRoleDesc(), FileVO.class);
        String oldCapability = iapPlatform.getCapability();

        iapPlatformMapper.deleteById(id);

        doDeleteAfter(id);

        fileUploadService.deleteFileByFileVO(ArraysExtendUtil.mergerArraysList(oldAccessBill, oldInterfaceDesc, oldOtherDesc, oldRoleDesc), true, false);
        fileUploadService.deleteFileByURL(ImageUtil.getImgTagUrl(oldCapability), true, false);
    }

    /**
     * 批量删除
     *
     * @param ids
     */
    public void batchDelete(List<Integer> ids) {
        ids.forEach(id -> {
            delete(id);
        });
    }

    /**
     * 删除后操作
     *
     * @param id
     */
    public void doDeleteAfter(Integer id) {
        //删除元数据
        iapDataModelService.deleteByIapPlatformId(id);
    }

    /**
     * 查询系统名称是否存在
     *
     * @param id
     * @param name
     * @return
     */
    public Boolean checkNameExists(Integer id, String name) {
        return iapPlatformMapper.checkNameExists(id, name);
    }
}
